package com.vhall.component.service.room.impl;

import com.vhall.component.dao.room.RecordOfRoomMapper;
import com.vhall.component.entity.record.RecordEntity;
import com.vhall.component.plugin.common.annotation.RedisSpinLock;
import com.vhall.component.plugin.common.constant.RedisKey;
import com.vhall.component.plugin.common.utils.JsonUtil;
import com.vhall.component.service.room.RoomCacheLockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author yuanzh
 */
@Slf4j
@Service
public class RoomCacheLockServiceImpl implements RoomCacheLockService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RecordOfRoomMapper recordOfRoomMapper;

    @Override
    public RecordEntity getCachedWarmRecordInfo(String warmVodId) {
        String cacheKey = RedisKey.WARM_VIDEO_INFO + warmVodId;
        String cachedStr = stringRedisTemplate.opsForValue().get(cacheKey);
        if (Objects.nonNull(cachedStr)) {
            return JsonUtil.objectFromJSONString(cachedStr, RecordEntity.class);
        }
        return doGetCachedWarmRecordInfoWithLock(warmVodId, cacheKey);
    }

    @RedisSpinLock(redisKey = "#cacheKey", expireTime = 10 * 1000)
    @Override
    public RecordEntity doGetCachedWarmRecordInfoWithLock(String warmVodId, String cacheKey) {
        String cachedStr = stringRedisTemplate.opsForValue().get(cacheKey);
        if (Objects.nonNull(cachedStr)) {
            return JsonUtil.objectFromJSONString(cachedStr, RecordEntity.class);
        }
        RecordEntity recordEntity = recordOfRoomMapper.findByVodId(warmVodId);
        // 缓存3秒有效期
        int expireSeconds = 3;
        // 若对应音视频不存在，重新缓存，并处理返回暖场视频id为空
        if (Objects.isNull(recordEntity)) {
            stringRedisTemplate.opsForValue().set(cacheKey, "", expireSeconds, TimeUnit.SECONDS);
            return null;
        }
        stringRedisTemplate.opsForValue().set(cacheKey, JsonUtil.toJsonString(recordEntity), expireSeconds, TimeUnit.SECONDS);
        return recordEntity;
    }
}
